package com.vicene.gmail.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.vicene.gmail.common.exception.NoStockException;
import com.vicene.gmail.common.mq.OrderTo;
import com.vicene.gmail.common.utils.R;
import com.vicene.gmail.common.vo.WeiBoLoginResp;
import com.vicene.gmail.order.constant.OrderConstant;
import com.vicene.gmail.order.dao.OrderItemDao;
import com.vicene.gmail.order.entity.OrderItemEntity;
import com.vicene.gmail.order.entity.PaymentInfoEntity;
import com.vicene.gmail.order.enume.OrderStatusEnum;
import com.vicene.gmail.order.feign.CartFeignService;
import com.vicene.gmail.order.feign.MemberFeignService;
import com.vicene.gmail.order.feign.ProductFeignService;
import com.vicene.gmail.order.feign.WmsFeignService;
import com.vicene.gmail.order.interceptor.LoginInterceptor;
import com.vicene.gmail.order.service.OrderItemService;
import com.vicene.gmail.order.service.PaymentInfoService;
import com.vicene.gmail.order.to.OrderCreateTo;
import com.vicene.gmail.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vicene.gmail.common.utils.PageUtils;
import com.vicene.gmail.common.utils.Query;

import com.vicene.gmail.order.dao.OrderDao;
import com.vicene.gmail.order.entity.OrderEntity;
import com.vicene.gmail.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<OrderSubmitVo>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderItemDao orderItemDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }



    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        WeiBoLoginResp weiBoLoginResp = LoginInterceptor.loginUser.get();

        //TODO 解决feign多线程丢失上下文的问题
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //远程收货地址
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() ->{

            //TODO 解决feign多线程丢失上下文的问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> addressVoList = memberFeignService.getAddress(weiBoLoginResp.getId());
            orderConfirmVo.setAddress(addressVoList);
        } , executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() ->{

            //TODO 解决feign多线程丢失上下文的问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items =  cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(items);
        } , executor).thenRunAsync(() ->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data =
                    (List<SkuStockVo>) hasStock.getData(new TypeReference<List<SkuStockVo>>(){});
            if(data != null){
                Map map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId ,SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }

        }, executor);
        //远程购物车数据


        Integer integration = weiBoLoginResp.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-" , "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + weiBoLoginResp.getId(), token , 30 , TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture , cartFuture).get();
        return orderConfirmVo;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {

        confirmVoThreadLocal.set(vo);

        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        WeiBoLoginResp weiBoLoginResp = LoginInterceptor.loginUser.get();
        response.setCode(0);
        //TODO 下单，创建订单，验令牌，锁库存，验价格，锁库存。。
        String orderToken = vo.getOrderToken();
        //TODO 1，验证令牌需要保证原子性 luna脚本  先查一致再删
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del' ,KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script , Long.class) ,
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + weiBoLoginResp.getId()) , orderToken);
        if(result == 0l){
            //失败
            response.setCode(1);
            return response;
        }else{
            //成功
            OrderCreateTo order = createOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();

            if(Math.abs(payAmount.subtract(payPrice).doubleValue()) <= 0.01){
                //金额对比
                saveOrder(order);

                //库存锁定 ，只有异常就抛出异常回滚
                WareSkuLockVo lockVo = new WareSkuLockVo();

                //订单号，所有订单项
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks =  order.getOrderItem().stream().map(item ->{
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);

                //远程操作锁定库存
                R r = wmsFeignService.orderLockStock(lockVo);
                if(r.getCode() == 0){
                    response.setOrder(order.getOrder());

                    //TODO 测试seata分布式事务
                    //int i = 1/0;

                    //TODO 订单创建成功发送消息给MQ  准备定时关单功能
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order" , order.getOrder());
                    //TODO 远程扣减积分
                    return response;
                }else{
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else{
                response.setCode(2);
                return response;
            }
        }
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + weiBoLoginResp.getId());
//        if(!StringUtils.isEmpty(orderToken) && orderToken.equals(redisToken)){
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + weiBoLoginResp.getId());
//
//            return response;
//        }else{
//            return response;
//        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity o =  this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn" , orderSn));
        return o;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询订单最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if(orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //关闭订单同时发送消息，释放库存

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try{
                //TODO 保证消息一定发出去，每个消息可以做日志记录
                //TODO 将失败的消息入库后，定时扫描重新发送
                rabbitTemplate.convertAndSend("order-event-exchange" ,"order.release.other" , orderTo);
            }catch (Exception e){

            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity =  this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2 , BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn",orderSn));

        payVo.setSubject(order_sn.get(0).getSkuName());
        payVo.setBody(order_sn.get(0).getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        WeiBoLoginResp weiBoLoginResp = LoginInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id" ,weiBoLoginResp.getId() ).orderByDesc("id")

        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order ->{
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn",order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 1，保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        //infoEntity.setCallbackTime(new Date(vo.getNotify_time()));
        paymentInfoService.save(infoEntity);

        //支付成功，修改订单状态
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED"))
        {
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo , OrderStatusEnum.PAYED.getCode());
        };
        return "success";
    }



    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        // orderDao.insert(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItem();

        orderItems.stream().forEach(orderItemEntity -> {
            orderItemDao.insert(orderItemEntity);
        });
        /**
         * TODO 此处seata报错io.seata.common.exception.NotSupportYetException: null
         * ### Error updating database.  Cause: io.seata.common.exception.NotSupportYetException
         * ### The error may exist in com/vicene/gmail/order/dao/OrderItemDao.java (best guess)
         * ### The error may involve com.vicene.gmail.order.dao.OrderItemDao.insert-Inline
         * ### The error occurred while setting parameters
         * 替换为dao执行上面代码
         */

        //orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();

        //1.订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity =  buildOrder(orderSn);
        createTo.setOrder(orderEntity);
        //2.获取所有订单项
        List<OrderItemEntity> itemEntities =  buildOrderItems(orderSn);
        createTo.setOrderItem(itemEntities);
        //3.验价
        computePrice(orderEntity ,itemEntities );
        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        for (OrderItemEntity entity : itemEntities){
            // BigDecimal decimal =  entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString()));
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }

        orderEntity.setTotalAmount(total);

        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(gift.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    private OrderEntity buildOrder(String orderSn) {
        WeiBoLoginResp weiBoLoginResp = LoginInterceptor.loginUser.get();

        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(weiBoLoginResp.getId());
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();

        //设置收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = (FareVo) fare.getData(new TypeReference<FareVo>(){});

        //运费信息
        entity.setFreightAmount(fareResp.getFare());

        //收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单相关信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        return entity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();

        if(!CollUtil.isEmpty(currentUserCartItems)){
            return currentUserCartItems.stream().map(cartItem ->{
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();

        //商品spu信息
        Long skuId = cartItem.getSkuId();
        SpuInfoVo spuInfoVo = (SpuInfoVo) productFeignService.getSpuInfoBySkuId(skuId).getData(new TypeReference<SpuInfoVo>(){});
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //商品sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttr() , ";"));
        itemEntity.setSkuQuantity(cartItem.getCount());

        //积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));

        //当前订单项的实际金额 总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount()).
                subtract(itemEntity.getPromotionAmount()).
                subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

}